"""
AI客服API视图
提供HTTP API接口
"""
from django.http import JsonResponse
from django.shortcuts import render
from django.views.decorators.csrf import csrf_exempt
from django.views.decorators.http import require_http_methods
import json
import logging
import os

from .qa_service import qa_service

logger = logging.getLogger(__name__)

def index(request):
    """主页视图"""
    return render(request, 'ai_assistant/index.html')

@csrf_exempt
@require_http_methods(["GET", "POST"])
def initialize(request):
    """初始化问答系统"""
    if request.method == "GET":
        # 获取初始化状态
        return JsonResponse({
            "code": 200,
            "data": {
                "is_initialized": qa_service.is_initialized,
                "db_exists": os.path.exists(qa_service.doc_processor.db_path)
            }
        })
    else:
        # 初始化系统
        try:
            data = json.loads(request.body) if request.body else {}
            force_rebuild = data.get("force_rebuild", False)
            
            success = qa_service.initialize(force_rebuild=force_rebuild)
            
            if success:
                return JsonResponse({
                    "code": 200,
                    "message": "问答系统初始化成功"
                })
            else:
                return JsonResponse({
                    "code": 500,
                    "message": "问答系统初始化失败"
                }, status=500)
                
        except Exception as e:
            logger.error(f"初始化问答系统失败: {str(e)}")
            return JsonResponse({
                "code": 500,
                "message": f"初始化问答系统失败: {str(e)}"
            }, status=500)

@csrf_exempt
@require_http_methods(["POST"])
def query(request):
    """问答查询"""
    try:
        data = json.loads(request.body) if request.body else {}
        question = data.get("question", "")
        
        if not question:
            return JsonResponse({
                "code": 400,
                "message": "请提供问题"
            }, status=400)
            
        # 获取回答
        answer = qa_service.answer(question)
        
        return JsonResponse({
            "code": 200,
            "data": {
                "question": question,
                "answer": answer
            }
        })
        
    except Exception as e:
        logger.error(f"问答查询失败: {str(e)}")
        return JsonResponse({
            "code": 500,
            "message": f"问答查询失败: {str(e)}"
        }, status=500)

@csrf_exempt
@require_http_methods(["POST"])
def get_document_info(request):
    """
    获取医疗文档信息
    """
    try:
        doc_processor = qa_service.doc_processor
        
        return JsonResponse({
            "code": 200,
            "status": "success",
            "data": {
                "doc_path": doc_processor.doc_path,
                "vector_db_path": doc_processor.vector_db_path,
                "is_processed": os.path.exists(doc_processor.vector_db_path),
                "chunks_count": len(doc_processor.chunks) if hasattr(doc_processor, 'chunks') and doc_processor.chunks else 0
            }
        })
    except Exception as e:
        logger.error(f"获取文档信息失败: {str(e)}")
        logger.error(traceback.format_exc())
        return JsonResponse({
            "code": 500,
            "status": "error",
            "message": f"获取文档信息失败: {str(e)}"
        }, status=500)
